import wx
import configparser
import subprocess
import threading
"""pyinstaller -F --win-no-prefer-redirects server.py"""


class Main(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None,-1,"远程穿透服务端设置",pos = (100,200),size = (500,400))
        self.p = wx.Panel(self, wx.ID_ANY)
        
        wx.StaticText(self.p,label="端口号",pos=(10,10))
        self.port_text = wx.TextCtrl(self.p,value="",pos = (50,10),size = (50,30))
        wx.StaticText(self.p,label="密钥",pos=(120,10))
        self.token_text = wx.TextCtrl(self.p,value="",pos = (150,10),size = (70,30))
        save_button = wx.Button(self.p,label = "启动",pos = (230,10),size = (50,24))
        save_button.Bind(wx.EVT_BUTTON,self.savefile)
        

        self.content_text= wx.TextCtrl(self.p,pos = (5,45),size = (475,300),style = wx.TE_MULTILINE)
        self.content_text.SetValue("请将对应端口映射到该服务器。")
        
        

    
    def savefile(self,event):
    
        serve_prot = self.port_text.GetValue()
        serve_token = self.port_text.GetValue()
        
        if serve_prot =='':
            self.content_text.SetValue("端口设置错误\n")
            return
        with open('s.ini', "r+") as f:
            f.truncate()
        
        cfg1 = "s.ini"

        conf = configparser.ConfigParser()
        conf.read(cfg1)

        conf.add_section("common")
        conf.sections()
        conf.set("common","privilege_token",serve_token)
        conf.set("common","bind_port",serve_prot)
        conf.set("common","authentication_timeout",'0')
        
        conf.sections()
        conf.write(open("s.ini","w+"))
        self.content_text.SetValue("s.ini配置已修改\n")
        
        RunService(self).start()
        
    def setMessageText(self,msg):
        self.content_text.SetValue(msg)
        
    def loop():
        """循环每隔N天重新关闭启动"""
        
        


    
class RunService(threading.Thread):
    def __init__(self,windows):
        threading.Thread.__init__(self)
        threading.Event().clear()
        self.windows = windows
        
    def run(self):
        wx.CallAfter(self.windows.setMessageText,"服务已启动\n")
        retcode = subprocess.call(["s.exe", "-c","s.ini"])
        # print("=================")
        # print(retcode)
        # print("============")
        
           

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = Main()
    frame.Show()
    app.MainLoop()

